<template>
  <div class="home-page">
    <!-- 顶部导航栏 -->
    <div class="top-navbar">
      <div class="navbar-container">
        <!-- 左侧logo -->
        <div class="navbar-left">
          <router-link to="/" class="logo-link">
            <svg class="logo-icon" viewBox="0 0 48 48" width="36" height="36" fill="none" xmlns="http://www.w3.org/2000/svg">
              <!-- 背景圆角矩形 -->
              <rect width="48" height="48" rx="12" fill="url(#logoGradient)"/>
              <!-- M字母设计 -->
              <path d="M12 32V16L18 24L24 16L30 24L36 16V32" stroke="white" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
              <!-- 小圆点装饰（像数学符号） -->
              <circle cx="18" cy="25" r="1.5" fill="white" opacity="0.8"/>
              <circle cx="30" cy="25" r="1.5" fill="white" opacity="0.8"/>
              <!-- 渐变定义 -->
              <defs>
                <linearGradient id="logoGradient" x1="0" y1="0" x2="48" y2="48" gradientUnits="userSpaceOnUse">
                  <stop offset="0%" style="stop-color:#667eea;stop-opacity:1" />
                  <stop offset="100%" style="stop-color:#764ba2;stop-opacity:1" />
                </linearGradient>
              </defs>
            </svg>
            <span class="logo">M-Learning</span>
          </router-link>
        </div>
        
        <!-- 中间导航菜单 -->
        <div class="navbar-center">
          <a href="#" class="nav-link">首页</a>
          <router-link to="/learning" class="nav-link">在线学习</router-link>
          <router-link to="/problems" class="nav-link">在线答题</router-link>
          <router-link to="/discussion" class="nav-link">学习社区</router-link>
          <router-link to="/profile" class="nav-link">个人中心</router-link>
        </div>
        
        <!-- 右侧用户信息 -->
        <div class="navbar-right">
          <!-- 私信 -->
          <div class="navbar-icon notification-icon" @click="openMessageList" title="私信">
            <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor">
              <path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/>
            </svg>
            <span v-if="unreadCount > 0" class="notification-badge">{{ unreadCount > 99 ? '99+' : unreadCount }}</span>
          </div>
          
          <!-- 连续学习天数 -->
          <div class="navbar-streak" @click="handleStreakClick">
            <svg viewBox="0 0 24 24" width="18" height="18" fill="#ff6b6b">
              <path d="M13.5.67s.74 2.65.74 4.8c0 2.06-1.35 3.73-3.41 3.73-2.07 0-3.63-1.67-3.63-3.73l.03-.36C5.21 7.51 4 10.62 4 14c0 4.42 3.58 8 8 8s8-3.58 8-8C20 8.61 17.41 3.8 13.5.67zM11.71 19c-1.78 0-3.22-1.4-3.22-3.14 0-1.62 1.05-2.76 2.81-3.12 1.77-.36 3.6-1.21 4.62-2.58.39 1.29.59 2.65.59 4.04 0 2.65-2.15 4.8-4.8 4.8z"/>
            </svg>
            <span class="streak-number">{{ continuousDays }}</span>
          </div>
          
          <!-- 用户头像和下拉菜单 -->
          <div class="user-dropdown" @mouseenter="showUserMenu = true" @mouseleave="showUserMenu = false">
            <div class="user-info-trigger">
              <div class="user-avatar" @click="handleAvatarClick">
                <img 
                  v-if="userInfo && userInfo.avatar" 
                  :src="getAvatarUrl(userInfo.avatar)" 
                  alt="头像"
                />
                <span v-else class="avatar-placeholder">
                  {{ userInfo?.nickname?.charAt(0) || userInfo?.phone?.charAt(userInfo.phone.length - 1) || '未' }}
                </span>
              </div>
              <span class="user-display-name">{{ userInfo?.nickname || userInfo?.phone || '未登录' }}</span>
            </div>
            
            <!-- 下拉菜单 -->
            <transition name="fade">
              <div v-if="showUserMenu" class="dropdown-menu">
                <div class="user-info-box">
                  <div class="user-name">{{ userInfo?.nickname || userInfo?.phone || '未登录' }}</div>
                  <div class="user-role">{{ userRoleText }}</div>
                </div>
                <div class="dropdown-divider"></div>
                <router-link to="/profile" class="dropdown-item">
                  <span class="icon">👤</span>
                  个人资料
                </router-link>
                <router-link to="/my-learning" class="dropdown-item">
                  <span class="icon">📚</span>
                  我的学习
                </router-link>
                <router-link to="/my-posts" class="dropdown-item">
                  <span class="icon">💬</span>
                  我的帖子
                </router-link>
                <div class="dropdown-divider"></div>
                <a href="#" class="dropdown-item" @click.prevent="handleLogout">
                  <span class="icon">🚪</span>
                  退出登录
                </a>
              </div>
            </transition>
          </div>
        </div>
        
        <!-- 头像上传输入框（隐藏） -->
        <input 
          ref="avatarInput"
          type="file" 
          accept="image/jpeg,image/jpg,image/png,image/gif"
          @change="handleAvatarChange"
          style="display: none"
        />
      </div>
    </div>
    
    <!-- 主要内容区域 -->
    <div class="main-content">
      <div class="content-wrapper">
        <!-- 左侧内容区 -->
        <div class="content-left">
          <!-- 轮播图 -->
          <Carousel :slides="banners" v-if="banners.length > 0" />
          
          <!-- 学习计划推荐 -->
          <section class="section learning-plans">
            <div class="section-header">
              <h2 class="section-title">学习计划</h2>
              <a href="#" class="section-more">更多></a>
            </div>
            <div class="plan-cards">
              <div 
                v-for="plan in learningPlans" 
                :key="plan.id"
                class="plan-card"
                :class="plan.colorClass"
              >
                <div class="plan-icon">
                  <span>{{ plan.icon }}</span>
                </div>
                <div class="plan-content">
                  <h3 class="plan-title">{{ plan.title }}</h3>
                  <p class="plan-desc">{{ plan.description }}</p>
                  <div class="plan-meta">
                    <span>{{ plan.problemCount }}题</span>
                    <span>{{ plan.studentCount }}人学习</span>
                  </div>
                </div>
              </div>
            </div>
          </section>
          
          <!-- 学习主题推荐 -->
          <section class="section learning-topics">
            <div class="section-header">
              <h2 class="section-title">热门学习主题</h2>
            </div>
            <div class="topic-tabs">
              <span 
                v-for="tab in topicTabs" 
                :key="tab.key"
                class="topic-tab"
                :class="{ active: activeTab === tab.key }"
                @click="handleTabChange(tab.key)"
              >
                {{ tab.label }}
              </span>
            </div>
            <div class="topic-list">
              <div 
                v-for="topic in filteredTopics" 
                :key="topic.id"
                class="topic-item"
              >
                <div class="topic-icon">{{ topic.icon }}</div>
                <div class="topic-info">
                  <h4 class="topic-title">{{ topic.title }}</h4>
                  <p class="topic-desc">{{ topic.description }}</p>
                  <div class="topic-meta">
                    <span>{{ topic.problemCount }}题</span>
                    <span :class="topic.difficulty">{{ topic.difficulty }}</span>
                  </div>
                </div>
              </div>
            </div>
          </section>
          
          <!-- 特色课程 -->
          <section class="section featured-courses">
            <div class="section-header">
              <h2 class="section-title">特色课程</h2>
              <a href="#" class="section-more">更多></a>
            </div>
            <div class="course-grid">
              <div 
                v-for="course in featuredCourses" 
                :key="course.id"
                class="course-card"
              >
                <div class="course-image" :style="{ background: getRandomGradient() }">
                  <div class="course-badge">{{ course.badge }}</div>
                </div>
                <div class="course-info">
                  <h4 class="course-title">{{ course.title }}</h4>
                  <div class="course-meta">
                    <span class="meta-item">{{ course.studentCount }}人学习</span>
                    <span class="meta-item">{{ course.difficulty }}</span>
                  </div>
                </div>
              </div>
            </div>
          </section>
        </div>
        
        <!-- 右侧边栏 -->
        <div class="content-right">
          <!-- 每日一题 -->
          <div class="widget daily-problem">
            <div class="widget-header">
              <span class="widget-icon">📅</span>
              <h3 class="widget-title">每日一题</h3>
            </div>
            <div class="widget-content">
              <div class="calendar">
                <div class="calendar-controls">
                  <button @click="prevMonth" class="month-btn">&lt;</button>
                  <span class="current-month">{{ currentYear }}年{{ currentMonth }}月</span>
                  <button @click="nextMonth" class="month-btn">&gt;</button>
                </div>
                <div class="calendar-header">
                  <span class="day">周一</span>
                  <span class="day">周二</span>
                  <span class="day">周三</span>
                  <span class="day">周四</span>
                  <span class="day">周五</span>
                  <span class="day weekend">周六</span>
                  <span class="day weekend">周日</span>
                </div>
                <div class="calendar-dates">
                  <span 
                    v-for="date in calendarDates" 
                    :key="date.key"
                    :class="['date', {
                      'other-month': date.isOtherMonth,
                      'today': date.isToday,
                      'has-record': date.hasLearningRecord
                    }]"
                  >
                    {{ date.day }}
                    <span v-if="date.hasLearningRecord" class="record-dot"></span>
                  </span>
                </div>
              </div>
              <div class="problem-info">
                <!-- 题目内容 - 平滑切换 -->
                <transition name="slide-fade" mode="out-in">
                  <div v-if="dailyProblem" :key="dailyProblem.problemId" class="problem-content-wrapper">
                    <div class="problem-number">第 {{ dailyProblem.problemId }} 题</div>
                    <h4 class="problem-title" v-html="renderedDailyProblemTitle"></h4>
                    <p class="problem-desc" v-html="renderedDailyProblemDesc"></p>
                    <div class="problem-tags" v-if="dailyProblem.tags && dailyProblem.tags.length">
                      <span class="tag" v-for="tag in dailyProblem.tags" :key="tag">{{ tag }}</span>
                    </div>
                    <button class="problem-btn" @click="startDailyProblem">开始答题</button>
                  </div>
                  
                  <!-- 无题目 -->
                  <div v-else key="no-problem" class="no-problem">
                    <p>暂无题目</p>
                  </div>
                </transition>
              </div>
            </div>
          </div>
          
          <!-- 学习统计 -->
          <div class="widget learning-stats" v-if="userStats">
            <div class="widget-header">
              <span class="widget-icon">📊</span>
              <h3 class="widget-title">学习统计</h3>
            </div>
            <div class="widget-content">
              <div class="stat-item">
                <div class="stat-label">本周答题</div>
                <div class="stat-value">{{ userStats.weekProblems || 0 }}题</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">连续学习</div>
                <div class="stat-value">{{ userStats.continuousDays || 0 }}天</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">总学习时长</div>
                <div class="stat-value">{{ userStats.totalHours || 0 }}小时</div>
              </div>
            </div>
          </div>
          
          <!-- 热门讨论 -->
          <div class="widget hot-discussions" v-if="hotDiscussions.length > 0">
            <div class="widget-header">
              <span class="widget-icon">🔥</span>
              <h3 class="widget-title">热门讨论</h3>
            </div>
            <div class="widget-content">
              <div 
                v-for="discussion in hotDiscussions" 
                :key="discussion.id"
                class="discussion-item"
              >
                <h4 class="discussion-title">{{ discussion.title }}</h4>
                <div class="discussion-meta">
                  <span>{{ discussion.views }}次浏览</span>
                  <span>{{ discussion.replies }}条回复</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 私信列表 -->
    <MessageList
      v-if="showMessageList"
      @close="closeMessageList"
      @openChat="openMessageDialog"
    />

    <!-- 私信对话 -->
    <MessageDialog
      v-if="showMessageDialog"
      :targetUser="messageTargetUser"
      @close="closeMessageDialog"
      @back="backToMessageList"
    />

    <!-- Toast提示 -->
    <Toast ref="toastRef" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import Carousel from '../components/Carousel.vue'
import Toast from '../components/Toast.vue'
import { uploadAvatar, getLearningStats, getLearningRecordDates } from '../api/user'
import { getDailyRandomProblem } from '../api/problem'
import { getAvatarUrl } from '../utils/url'
import { renderMathInHTML } from '../utils/renderMath'
import MessageList from '../components/MessageList.vue'
import MessageDialog from '../components/MessageDialog.vue'
import { getUnreadCount } from '../api/message'
// import { getHomeAllData, getLearningTopics } from '../api/home' // 不再使用API

const router = useRouter()
const userStore = useUserStore()

const userInfo = computed(() => userStore.userInfo)
const userRoleText = computed(() => {
  if (!userInfo.value) return '未登录'
  console.log('当前用户信息:', userInfo.value)
  console.log('用户角色字段:', userInfo.value.role)
  return userInfo.value.role === 'admin' ? '管理员' : '普通用户'
})
const showUserMenu = ref(false)
const avatarInput = ref(null)
const toastRef = ref(null)

// 导航栏功能数据
const unreadCount = ref(0) // 未读私信数量
const continuousDays = ref(0) // 连续学习天数（从API加载）

// 私信功能
const showMessageList = ref(false)
const showMessageDialog = ref(false)
const messageTargetUser = ref(null)

// 数据状态
const banners = ref([])
const learningPlans = ref([])
const topics = ref([])
const featuredCourses = ref([])
const dailyProblem = ref(null)
const userStats = ref(null)
const hotDiscussions = ref([])

// 日历相关
const currentYear = ref(new Date().getFullYear())
const currentMonth = ref(new Date().getMonth() + 1)
const learningRecords = ref([]) // 学习记录日期数组，格式：['2025-01-01', '2025-01-15']

// 定时器
let dailyProblemTimer = null

// 渲染每日题目的 LaTeX 公式
const renderedDailyProblemTitle = computed(() => {
  if (!dailyProblem.value?.title) return ''
  return renderMathInHTML(dailyProblem.value.title)
})

const renderedDailyProblemDesc = computed(() => {
  if (!dailyProblem.value?.description) return ''
  return renderMathInHTML(dailyProblem.value.description)
})

// 生成日历数据
const calendarDates = computed(() => {
  const year = currentYear.value
  const month = currentMonth.value
  
  // 当月第一天是星期几（0=周日，1=周一，...，6=周六）
  const firstDay = new Date(year, month - 1, 1).getDay()
  // 调整为周一开始（0=周一，1=周二，...，6=周日）
  const firstDayOfWeek = firstDay === 0 ? 6 : firstDay - 1
  
  // 当月天数
  const daysInMonth = new Date(year, month, 0).getDate()
  
  // 上个月天数
  const prevMonthDays = new Date(year, month - 1, 0).getDate()
  
  const dates = []
  const today = new Date()
  const todayStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`
  
  // 填充上个月的日期
  for (let i = firstDayOfWeek - 1; i >= 0; i--) {
    const day = prevMonthDays - i
    const dateStr = `${month === 1 ? year - 1 : year}-${String(month === 1 ? 12 : month - 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`
    dates.push({
      day,
      key: `prev-${day}`,
      isOtherMonth: true,
      isToday: false,
      hasLearningRecord: learningRecords.value.includes(dateStr)
    })
  }
  
  // 填充当月的日期
  for (let day = 1; day <= daysInMonth; day++) {
    const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`
    dates.push({
      day,
      key: `current-${day}`,
      isOtherMonth: false,
      isToday: dateStr === todayStr,
      hasLearningRecord: learningRecords.value.includes(dateStr)
    })
  }
  
  // 填充下个月的日期（填满6行 = 42个格子）
  const remainingDays = 42 - dates.length
  for (let day = 1; day <= remainingDays; day++) {
    const dateStr = `${month === 12 ? year + 1 : year}-${String(month === 12 ? 1 : month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`
    dates.push({
      day,
      key: `next-${day}`,
      isOtherMonth: true,
      isToday: false,
      hasLearningRecord: learningRecords.value.includes(dateStr)
    })
  }
  
  return dates
})

// 主题标签
const topicTabs = [
  { key: 'all', label: '全部' },
  { key: 'algebra', label: '代数' },
  { key: 'geometry', label: '几何' },
  { key: 'analysis', label: '分析' }
]

const activeTab = ref('all')

const filteredTopics = computed(() => {
  if (activeTab.value === 'all') {
    return topics.value
  }
  return topics.value.filter(topic => topic.category === activeTab.value)
})

// 随机渐变色
const gradients = [
  'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
  'linear-gradient(135deg, #11998e 0%, #38ef7d 100%)',
  'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
  'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
  'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)'
]

function getRandomGradient() {
  return gradients[Math.floor(Math.random() * gradients.length)]
}

function handleTabChange(tabKey) {
  activeTab.value = tabKey
  // 可选：重新加载该分类的数据
  loadTopics(tabKey)
}

async function loadTopics(category) {
  // 不再调用API，直接使用本地模拟数据
  // 如果需要可以在这里根据 category 过滤 topics.value
}

// 加载每日随机题目
async function loadDailyProblem() {
  try {
    const res = await getDailyRandomProblem()
    if (res.code === 200 && res.data) {
      // 直接更新题目，Vue的transition会自动处理动画
      dailyProblem.value = res.data
      console.log('✅ 每日题目已刷新:', res.data.title)
    } else {
      console.log('⚠️ 暂无题目')
      dailyProblem.value = null
    }
  } catch (error) {
    console.error('获取每日题目失败:', error)
    // 失败时保留上一次的题目
  }
}

// 启动每日题目自动刷新（15秒）
function startDailyProblemRefresh() {
  // 立即加载一次
  loadDailyProblem()
  
  // 每15秒刷新一次
  dailyProblemTimer = setInterval(() => {
    loadDailyProblem()
  }, 15000) // 15秒 = 15000毫秒
  
  console.log('⏰ 每日题目自动刷新已启动（15秒间隔）')
}

// 停止每日题目自动刷新
function stopDailyProblemRefresh() {
  if (dailyProblemTimer) {
    clearInterval(dailyProblemTimer)
    dailyProblemTimer = null
    console.log('⏸️ 每日题目自动刷新已停止')
  }
}

async function loadHomeData() {
  // 直接使用本地模拟数据，不对接后端API
  await setMockData()
}

// 设置模拟数据
async function setMockData() {
  // 轮播图数据
  banners.value = [
    {
      id: 1,
      imageUrl: 'https://images.unsplash.com/photo-1509228468518-180dd4864904?w=1200&h=400&fit=crop',
      title: '探索数学的奇妙世界',
      description: '从基础到高级，全面掌握数学知识',
      linkUrl: '/learn'
    },
    {
      id: 2,
      imageUrl: 'https://images.unsplash.com/photo-1451187580459-43490279c0fa?w=1200&h=400&fit=crop',
      title: '在线互动学习',
      description: '与老师和同学实时互动，高效学习',
      linkUrl: '/learn'
    },
    {
      id: 3,
      imageUrl: 'https://images.unsplash.com/photo-1516321318423-f06f85e504b3?w=1200&h=400&fit=crop',
      title: '每日一题，持续进步',
      description: '养成良好学习习惯，不断提升数学能力',
      linkUrl: '/daily'
    }
  ]
  
  // 学习计划数据
  learningPlans.value = [
    {
      id: 1,
      title: '基础代数',
      description: '掌握代数基础概念和计算方法',
      problemCount: 120,
      studentCount: 1500,
      icon: '📊',
      colorClass: 'purple'
    },
    {
      id: 2,
      title: '几何图形',
      description: '学习几何图形的性质和计算',
      problemCount: 100,
      studentCount: 980,
      icon: '📐',
      colorClass: 'green'
    },
    {
      id: 3,
      title: '函数分析',
      description: '深入理解函数的性质和变化规律',
      problemCount: 150,
      studentCount: 1200,
      icon: '📈',
      colorClass: 'orange'
    }
  ]
  
  // 学习主题数据
  topics.value = [
    {
      id: 1,
      title: '线性方程组',
      description: '学习如何求解线性方程组',
      problemCount: 50,
      difficulty: '初级',
      icon: '🔢',
      category: 'algebra'
    },
    {
      id: 2,
      title: '二次函数',
      description: '掌握二次函数的图像和性质',
      problemCount: 45,
      difficulty: '中级',
      icon: '📉',
      category: 'algebra'
    },
    {
      id: 3,
      title: '三角形',
      description: '了解三角形的性质和定理',
      problemCount: 40,
      difficulty: '初级',
      icon: '🔺',
      category: 'geometry'
    },
    {
      id: 4,
      title: '函数与极限',
      description: '深入理解函数的性质和极限的计算',
      problemCount: 60,
      difficulty: '高级',
      icon: '∞',
      category: 'analysis'
    }
  ]
  
  // 特色课程数据
  featuredCourses.value = [
    {
      id: 1,
      title: '数学基础强化',
      description: '系统学习数学基础知识',
      studentCount: 2300,
      difficulty: '初级',
      badge: '热门'
    },
    {
      id: 2,
      title: '高等数学进阶',
      description: '深入学习高等数学理论',
      studentCount: 1800,
      difficulty: '高级',
      badge: '推荐'
    },
    {
      id: 3,
      title: '竞赛数学',
      description: '备战数学竞赛专题训练',
      studentCount: 950,
      difficulty: '高级',
      badge: '精选'
    }
  ]
  
  // 每日一题数据 - 改为从API动态加载，不再使用模拟数据
  
  // 从API加载真实的学习统计数据
  try {
    const statsRes = await getLearningStats()
    if (statsRes.code === 200) {
      const data = statsRes.data
      // 将分钟转换为小时（保留1位小数）
      const totalHours = data.totalStudyMinutes ? (data.totalStudyMinutes / 60).toFixed(1) : 0
      
      userStats.value = {
        weekProblems: data.weekProblems || 0,
        continuousDays: data.continuousDays || 0,
        totalHours: parseFloat(totalHours)
      }
      continuousDays.value = data.continuousDays || 0
      
      console.log('✅ 学习统计已加载:', userStats.value)
    }
  } catch (error) {
    console.error('获取学习统计失败:', error)
    // 失败时使用默认值
    userStats.value = {
      weekProblems: 0,
      continuousDays: 0,
      totalHours: 0
    }
  }
  
  // 热门讨论数据
  hotDiscussions.value = [
    {
      id: 1,
      title: '如何快速掌握微积分基础知识？',
      views: 1580,
      replies: 23
    },
    {
      id: 2,
      title: '线性代数在机器学习中的应用',
      views: 892,
      replies: 15
    },
    {
      id: 3,
      title: '高考数学压轴题解题技巧分享',
      views: 2145,
      replies: 47
    }
  ]
  
  console.log('✅ 已加载本地模拟数据')
}

async function handleLogout() {
  // 关闭 WebSocket 连接
  const { closeWebSocket } = await import('../utils/websocket')
  closeWebSocket()
  
  userStore.logout()
  router.push('/login')
}

// 消息通知

// 连续学习天数
function handleStreakClick() {
  const days = continuousDays.value
  const title = days > 0 ? `恭喜！您已连续学习 ${days} 天 🔥` : '还未开始学习'
  const message = days > 0 ? `继续保持，再接再厉！` : '今天开始学习吧！'
  
  toastRef.value?.show({
    title,
    message,
    type: 'fire'
  })
}

// 日历月份切换
function prevMonth() {
  if (currentMonth.value === 1) {
    currentYear.value--
    currentMonth.value = 12
  } else {
    currentMonth.value--
  }
  // 切换月份后重新加载学习记录
  loadLearningRecords()
}

function nextMonth() {
  if (currentMonth.value === 12) {
    currentYear.value++
    currentMonth.value = 1
  } else {
    currentMonth.value++
  }
  // 切换月份后重新加载学习记录
  loadLearningRecords()
}

// 开始每日答题
function startDailyProblem() {
  if (dailyProblem.value && dailyProblem.value.problemId) {
    router.push(`/problem/${dailyProblem.value.problemId}`)
  }
}

// 加载学习记录（从后端API获取）
async function loadLearningRecords() {
  try {
    const res = await getLearningRecordDates({
      year: currentYear.value,
      month: currentMonth.value
    })
    
    if (res.code === 200) {
      learningRecords.value = res.data.dates || []
      console.log(`✅ 加载学习记录成功：${currentYear.value}年${currentMonth.value}月，共${res.data.totalDays}天`)
    }
  } catch (error) {
    console.error('获取学习记录失败:', error)
    // 失败时使用空数组，不显示小红点
    learningRecords.value = []
  }
}

function handleAvatarClick() {
  avatarInput.value.click()
}

async function handleAvatarChange(event) {
  const file = event.target.files[0]
  if (!file) return

  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    alert('请选择图片文件')
    return
  }

  // 验证文件大小（5MB）
  if (file.size > 5 * 1024 * 1024) {
    alert('图片大小不能超过 5MB')
    return
  }

  try {
    const formData = new FormData()
    formData.append('file', file)

    const res = await uploadAvatar(formData)
    if (res.data && res.data.url) {
      // 更新用户信息（保存相对路径）
      userStore.updateUserInfo({ avatar: res.data.url })
      console.log('头像上传成功:', res.data.url)
      alert('头像上传成功')
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    alert(error.message || '头像上传失败，请重试')
  }

  // 清空input，允许重复选择同一文件
  event.target.value = ''
}

onMounted(() => {
  // 检查登录状态
  console.log('Home mounted - Token:', userStore.token)
  console.log('Home mounted - UserInfo:', userStore.userInfo)
  
  if (!userStore.token || !userStore.userInfo) {
    console.warn('用户未登录，跳转到登录页')
    router.push('/login')
    return
  }
  
  loadHomeData()
  loadUnreadCount()
  loadLearningRecords() // 加载学习记录（日历小红点）
  startDailyProblemRefresh() // 启动每日题目自动刷新
})

// 组件卸载时清理定时器
onUnmounted(() => {
  stopDailyProblemRefresh()
})

// 加载未读私信数量
async function loadUnreadCount() {
  try {
    const res = await getUnreadCount()
    if (res.code === 200) {
      unreadCount.value = res.data.count || 0
    }
  } catch (error) {
    console.error('获取未读消息数失败:', error)
    // 使用模拟数据
    unreadCount.value = 3
  }
}

// 打开私信列表
function openMessageList() {
  showMessageList.value = true
}

// 关闭私信列表
function closeMessageList() {
  showMessageList.value = false
}

// 打开私信对话
function openMessageDialog(user) {
  showMessageList.value = false
  messageTargetUser.value = user
  showMessageDialog.value = true
}

// 关闭私信对话
function closeMessageDialog() {
  showMessageDialog.value = false
  messageTargetUser.value = null
  // 刷新未读消息数
  loadUnreadCount()
}

// 返回私信列表
function backToMessageList() {
  showMessageDialog.value = false
  showMessageList.value = true
}
</script>

<style scoped lang="scss">
.home-page {
  min-height: 100vh;
  background: #f8f9fa;
}

// 顶部导航栏
.top-navbar {
  background: #fff;
  border-bottom: 1px solid #e8e8e8;
  position: sticky;
  top: 0;
  z-index: 1000;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
}

.navbar-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 24px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.navbar-left {
  .logo-link {
    text-decoration: none;
    display: flex;
    align-items: center;
    gap: 12px;
    transition: transform 0.3s;
    
    &:hover {
      transform: translateY(-2px);
      
      .logo-icon {
        transform: rotate(5deg) scale(1.05);
      }
    }
    
    .logo-icon {
      display: block;
      transition: transform 0.3s;
      filter: drop-shadow(0 2px 8px rgba(102, 126, 234, 0.3));
    }
    
    .logo {
      font-size: 24px;
      font-weight: bold;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
      letter-spacing: 0.5px;
    }
  }
}

.navbar-center {
  display: flex;
  gap: 32px;
  
  .nav-link {
    color: #333;
    text-decoration: none;
    font-size: 15px;
    transition: color 0.2s;
    
    &:hover {
      color: #667eea;
    }
  }
}

.navbar-right {
  position: relative;
  display: flex;
  align-items: center;
  gap: 20px;
}

// 导航栏图标通用样式
.navbar-icon {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #666;
  border-radius: 50%;
  transition: all 0.3s;
  position: relative;
  
  &:hover {
    background: #f5f5f5;
    color: #333;
  }
  
  svg {
    display: block;
  }
}

// 消息通知图标
.notification-icon {
  position: relative;
  
  .notification-badge {
    position: absolute;
    top: 2px;
    right: 2px;
    min-width: 16px;
    height: 16px;
    padding: 0 4px;
    background: #ff4757;
    color: white;
    font-size: 10px;
    font-weight: bold;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    line-height: 1;
    box-shadow: 0 2px 4px rgba(255, 71, 87, 0.3);
  }
}

// 连续学习天数
.navbar-streak {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  background: linear-gradient(135deg, #fff5f5 0%, #ffe5e5 100%);
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    background: linear-gradient(135deg, #ffeded 0%, #ffd5d5 100%);
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(255, 107, 107, 0.15);
  }
  
  svg {
    display: block;
    animation: flicker 2s infinite;
  }
  
  .streak-number {
    font-size: 14px;
    font-weight: 600;
    color: #ff6b6b;
    line-height: 1;
  }
}

@keyframes flicker {
  0%, 100% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.8;
    transform: scale(1.1);
  }
}

.user-dropdown {
  position: relative;
  
  .user-info-trigger {
    display: flex;
    align-items: center;
    gap: 10px;
    cursor: pointer;
    padding: 4px 12px 4px 4px;
    border-radius: 24px;
    transition: background 0.3s;
    
    &:hover {
      background: #f5f5f5;
    }
  }
  
  .user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    font-size: 16px;
    font-weight: bold;
    overflow: hidden;
    transition: transform 0.3s;
    flex-shrink: 0;
    
    &:hover {
      transform: scale(1.05);
    }
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
  
  .user-display-name {
    font-size: 14px;
    font-weight: 500;
    color: #333;
    white-space: nowrap;
    max-width: 120px;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

.dropdown-menu {
  position: absolute;
  top: 50px;
  right: 0;
  width: 240px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  padding: 12px 0;
  
  .user-info-box {
    padding: 12px 16px;
    
    .user-name {
      font-size: 15px;
      font-weight: 500;
      color: #333;
    }
    
    .user-id {
      font-size: 13px;
      color: #999;
      margin-top: 4px;
    }
    
    .user-role {
      font-size: 12px;
      color: #667eea;
      margin-top: 6px;
      padding: 2px 8px;
      background: rgba(102, 126, 234, 0.1);
      border-radius: 10px;
      display: inline-block;
      font-weight: 500;
    }
  }
  
  .dropdown-divider {
    height: 1px;
    background: #e8e8e8;
    margin: 8px 0;
  }
  
  .dropdown-item {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    color: #333;
    text-decoration: none;
    transition: background 0.2s;
    
    &:hover {
      background: #f5f5f5;
    }
    
    .icon {
      margin-right: 8px;
      font-size: 16px;
    }
  }
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.2s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

// 主要内容区域
.main-content {
  padding: 32px 0;
}

.content-wrapper {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 24px;
  display: grid;
  grid-template-columns: 1fr 320px;
  gap: 32px;
}

// 左侧内容
.content-left {
  display: flex;
  flex-direction: column;
  gap: 32px;
}

// 右侧边栏
.content-right {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

// 通用区块样式
.section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  .section-title {
    font-size: 20px;
    font-weight: 600;
    color: #333;
  }
  
  .section-more {
    color: #999;
    text-decoration: none;
    font-size: 14px;
    
    &:hover {
      color: #667eea;
    }
  }
}

// 学习计划卡片
.learning-plans {
  .plan-cards {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
  }
  
  .plan-card {
    border-radius: 12px;
    padding: 20px;
    display: flex;
    align-items: center;
    gap: 16px;
    transition: transform 0.2s, box-shadow 0.2s;
    cursor: pointer;
    
    &:hover {
      transform: translateY(-4px);
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
    }
    
    &.purple {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
    }
    
    &.green {
      background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
      color: white;
    }
    
    &.orange {
      background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
      color: white;
    }
    
    .plan-icon {
      font-size: 48px;
      flex-shrink: 0;
    }
    
    .plan-content {
      flex: 1;
      
      .plan-title {
        font-size: 18px;
        font-weight: 600;
        margin-bottom: 8px;
      }
      
      .plan-desc {
        font-size: 14px;
        opacity: 0.9;
        line-height: 1.5;
        margin-bottom: 8px;
      }
      
      .plan-meta {
        display: flex;
        gap: 16px;
        font-size: 13px;
        opacity: 0.8;
      }
    }
  }
}

// 学习主题
.learning-topics {
  .topic-tabs {
    display: flex;
    gap: 8px;
    margin-bottom: 20px;
    
    .topic-tab {
      padding: 8px 16px;
      border-radius: 20px;
      cursor: pointer;
      transition: all 0.2s;
      background: #f5f5f5;
      color: #666;
      
      &:hover {
        background: #e8e8e8;
      }
      
      &.active {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
      }
    }
  }
  
  .topic-list {
    display: grid;
    gap: 16px;
    
    .topic-item {
      display: flex;
      align-items: center;
      gap: 16px;
      padding: 16px;
      border-radius: 8px;
      background: #f8f9fa;
      transition: all 0.2s;
      cursor: pointer;
      
      &:hover {
        background: #e9ecef;
        transform: translateX(4px);
      }
      
      .topic-icon {
        font-size: 32px;
        flex-shrink: 0;
      }
      
      .topic-info {
        flex: 1;
        
        .topic-title {
          font-size: 16px;
          font-weight: 500;
          margin-bottom: 4px;
          color: #333;
        }
        
        .topic-desc {
          font-size: 14px;
          color: #666;
          line-height: 1.4;
          margin-bottom: 8px;
        }
        
        .topic-meta {
          display: flex;
          gap: 12px;
          font-size: 13px;
          color: #999;
          
          span {
            padding: 2px 8px;
            border-radius: 4px;
            background: #e9ecef;
            
            &.初级 {
              background: #d4edda;
              color: #155724;
            }
            &.中级 {
              background: #fff3cd;
              color: #856404;
            }
            &.高级 {
              background: #f8d7da;
              color: #721c24;
            }
          }
        }
      }
    }
  }
}

// 特色课程
.featured-courses {
  .course-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
  }
  
  .course-card {
    border-radius: 12px;
    overflow: hidden;
    background: #f8f9fa;
    transition: transform 0.2s, box-shadow 0.2s;
    cursor: pointer;
    
    &:hover {
      transform: translateY(-4px);
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
    }
    
    .course-image {
      height: 120px;
      position: relative;
      
      .course-badge {
        position: absolute;
        top: 12px;
        right: 12px;
        background: white;
        padding: 4px 12px;
        border-radius: 12px;
        font-size: 12px;
        font-weight: 500;
      }
    }
    
    .course-info {
      padding: 16px;
      
      .course-title {
        font-size: 16px;
        font-weight: 500;
        margin-bottom: 8px;
        color: #333;
      }
      
      .course-meta {
        display: flex;
        gap: 16px;
        font-size: 14px;
        color: #999;
      }
    }
  }
}

// 右侧小部件
.widget {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  
  .widget-header {
    padding: 16px 20px;
    border-bottom: 1px solid #e8e8e8;
    display: flex;
    align-items: center;
    gap: 8px;
    
    .widget-icon {
      font-size: 20px;
    }
    
    .widget-title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }
  }
  
  .widget-content {
    padding: 20px;
  }
}

// 每日一题
.daily-problem {
  .calendar {
    margin-bottom: 20px;
    
    .calendar-controls {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 16px;
      
      .month-btn {
        width: 32px;
        height: 32px;
        border: 1px solid #ddd;
        background: white;
        border-radius: 4px;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.2s;
        font-size: 16px;
        
        &:hover {
          background: #f5f5f5;
          border-color: #667eea;
          color: #667eea;
        }
      }
      
      .current-month {
        font-size: 15px;
        font-weight: 600;
        color: #333;
      }
    }
    
    .calendar-header {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      gap: 4px;
      margin-bottom: 8px;
      
      .day {
        font-size: 12px;
        color: #666;
        text-align: center;
        font-weight: 500;
        
        &.weekend {
          color: #f56c6c;
        }
      }
    }
    
    .calendar-dates {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      gap: 4px;
      
      .date {
        aspect-ratio: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        color: #666;
        border-radius: 4px;
        position: relative;
        transition: all 0.2s;
        
        &.other-month {
          color: #ccc;
        }
        
        &.today {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          color: white;
          border-radius: 50%;
          font-weight: 600;
        }
        
        &.has-record .record-dot {
          position: absolute;
          bottom: 2px;
          width: 4px;
          height: 4px;
          background: #ff4d4f;
          border-radius: 50%;
        }
        
        &.today.has-record .record-dot {
          background: white;
        }
        
        &:not(.other-month):not(.today):hover {
          background: #f5f5f5;
        }
      }
    }
  }
  
  .problem-info {
    position: relative;
    min-height: 180px; // 防止切换时高度抖动
    
    .problem-number {
      font-size: 12px;
      color: #999;
      margin-bottom: 8px;
    }
    
    .problem-title {
      font-size: 18px;
      font-weight: 600;
      margin-bottom: 8px;
      color: #333;
    }
    
    .problem-desc {
      font-size: 14px;
      color: #666;
      margin-bottom: 12px;
      line-height: 1.5;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }
    
    .problem-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 6px;
      margin-bottom: 16px;
      
      .tag {
        padding: 3px 10px;
        background: #e9ecef;
        border-radius: 4px;
        font-size: 12px;
        color: #666;
      }
    }
    
    .problem-btn {
      width: 100%;
      padding: 10px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border: none;
      border-radius: 6px;
      cursor: pointer;
      font-size: 14px;
      transition: opacity 0.2s;
      
      &:hover {
        opacity: 0.9;
      }
    }
    
    // 无题目
    .no-problem {
      text-align: center;
      padding: 30px 0;
      color: #999;
      font-size: 14px;
    }
  }
}

// 加载动画
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

// 题目切换动画 - 优雅的滑动淡入淡出效果
.slide-fade-enter-active {
  transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
}

.slide-fade-leave-active {
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
}

.slide-fade-enter-from {
  opacity: 0;
  transform: translateX(20px);
}

.slide-fade-leave-to {
  opacity: 0;
  transform: translateX(-20px);
}

// 题目内容包裹器
.problem-content-wrapper {
  width: 100%;
}

// LaTeX 公式样式
:deep(.math-display) {
  display: block;
  margin: 12px 0;
  text-align: center;
  overflow-x: auto;
  
  .katex-display {
    margin: 0;
  }
}

:deep(.math-inline) {
  display: inline;
  
  .katex {
    font-size: 1em;
  }
}

:deep(.math-error) {
  color: #cf222e;
  background: #ffebe9;
  padding: 2px 6px;
  border-radius: 3px;
  font-family: monospace;
  font-size: 12px;
}

// 学习统计
.learning-stats {
  .stat-item {
    padding: 12px 0;
    
    &:not(:last-child) {
      border-bottom: 1px solid #e8e8e8;
    }
    
    .stat-label {
      font-size: 14px;
      color: #999;
      margin-bottom: 4px;
    }
    
    .stat-value {
      font-size: 20px;
      font-weight: 600;
      color: #333;
    }
  }
}

// 热门讨论
.hot-discussions {
  .discussion-item {
    padding: 12px 0;
    
    &:not(:last-child) {
      border-bottom: 1px solid #e8e8e8;
    }
    
    .discussion-title {
      font-size: 14px;
      font-weight: 500;
      margin-bottom: 8px;
      color: #333;
      cursor: pointer;
      transition: color 0.2s;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      
      &:hover {
        color: #667eea;
      }
    }
    
    .discussion-meta {
      display: flex;
      gap: 16px;
      font-size: 12px;
      color: #999;
    }
  }
}
</style>
